import $lodash from "lodash";
const pako = require("pako");
export const webSocketMixin = {
  data() {
    return {
      wsFlags: {
        runing: false,
        history: false,
        sub: false,
      },
      subData: {
        sub: "market.bchusdt.kline.1min",
        id: "bchusdt",
      },
      lastBar: null,
    };
  },
  created() {},
  methods: {
    // 初始连接
    webSocket(e) {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
        return;
      }
      const self = this;
      if (e == "load") {
        // 实例化 socket
        self.websock = new WebSocket(self.wsUrl);
        // 监听 socket 连接
        self.websock.onopen = self.websockOpen;
        // 监听 socket 错误信息
        self.websock.onerror = self.websockError;
        // 监听 socket 消息
        self.websock.onmessage = self.websockMessage;
      }
    },

    // 链接状态
    websockOpen(e) {
      const self = this;
      self.wsFlags.runing = true;
      if (!self.wsFlags.sub) {
        self.websockSend(JSON.stringify(self.subData));
      }
      if (!self.wsFlags.history) {
        self.loadHistory();
      }
    },

    // 发送消息
    websockSend(msg) {
      // console.log(msg);
      const self = this;
      if (!this.wsFlags.runing) {
        alert("Websock 未建立");
        return false;
      }
      self.websock.send(msg);
    },

    loadHistory() {
      console.log(63);
      console.log(this.wsFlags.history);
      let requestK = {
        // 请求对应信息的数据
        req: "market.bchusdt.kline.1min",
        id: "bchusdt",
        from: Math.round(new Date().getTime() / 1000) - 1200,
        to: Math.round(new Date().getTime() / 1000),
      };
      this.websockSend(JSON.stringify(requestK));
    },

    // 错误
    websockError(e) {
      this.websockClose();
    },

    // 监听返回消息
    websockMessage(msg) {
      const self = this;
      self
        .unpack(msg.data)
        .then((data) => {
          if (data.hasOwnProperty("subbed") && data.status === "ok") {
            self.wsFlags.sub = true;
          }
          if (data.hasOwnProperty("tick")) {
            // self.websockClose();
            // console.log(self.onLoadedCallback);
            self.loadChartJIT(data.tick);
          }
          if (data.hasOwnProperty("data")) {
            console.log(self.wsFlags.history);
            console.log(data.data);
            console.log(typeof self.onLoadedCallback);
            if (typeof self.onLoadedCallback !== "function") {
              return;
            }
            self.onLoadedCallback(
              data.data.map(function(item) {
                return {
                  time: Number(item.id * 1000),
                  close: Number(item.close),
                  open: Number(item.open),
                  high: Number(item.high),
                  low: Number(item.low),
                  volume: Number(item.vol),
                };
              })
            );
            // this.websockClose();
            self.wsFlags.history = true;
          }
        })
        .catch((ping) => {
          self.websockSend(JSON.stringify({ pong: ping }));
        });
      return;
    },

    // 实时数据
    loadChartJIT(item) {
      const self = this;
      if (self.lastBar && self.lastBar.id >= item.id) {
        return;
      }
      console.log("loadChartJIT");
      console.log(item);
      self.lastBar = item;
      // console.log(typeof self.onRealtimeCallback);
      try {
        self.onRealtimeCallback({
          time: Number(item.id * 1000),
          close: Number(item.close),
          open: Number(item.open),
          high: Number(item.high),
          low: Number(item.low),
          volume: Number(item.vol),
        });
      } catch (e) {
        console.log(e);
      }
    },

    // 解压数据
    unpack(blob) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.onload = function(e) {
          let ploydata = new Uint8Array(e.target.result);
          let msg = pako.inflate(ploydata, { to: "string" });
          let data = JSON.parse(msg);
          // console.log(148);
          // console.log(data);
          if (data.hasOwnProperty("ping")) {
            reject(data.ping);
          } else {
            resolve(data);
          }
        };
        reader.readAsArrayBuffer(blob, "utf-8");
      });
    },

    // 连接关闭
    websockClose() {
      const self = this;
      self.websock.close();
    },
  },
};
